import { defineStore } from 'pinia'
import { SelfStorage } from '@/utils/secureLs'
import maintenance from '@/api/modules/maintenance.ts'
import { formatLang } from '@/utils/locale.ts'
import * as localeList from 'element-plus/es/locale/index'

interface SysGlobalModel {
    sysIsMobile: boolean
    sysLayout: string
    sysLang: string
    sysLangMessages: Record<string, any>
    sysColor: string
    sysDark: boolean
    sysMenuIsCollapse: boolean
    sysMenuUniqueOpened: boolean
    sysLayoutTags: boolean
    sysAutoExit: number
}

export const useSysGlobalStore = defineStore('sysGlobal', {
    state(): SysGlobalModel {
        return {
            // 移动端布局
            sysIsMobile: false,
            // 布局 [默认-default | 通栏-header | 经典-menu | 功能坞-dock（将关闭标签和面包屑栏）]
            sysLayout: 'default',
            // 语言，默认中文zh-cn,英文en
            sysLang: 'zh-cn',
            // 语言包
            sysLangMessages: {},
            // 主题颜色
            sysColor: '#409EFF',
            // 暗黑模式
            sysDark: false,
            // 菜单是否折叠 toggle
            sysMenuIsCollapse: false,
            // 菜单是否只保持一个子菜单的展开
            sysMenuUniqueOpened: false,
            // 多标签栏
            sysLayoutTags: true,
            // 自动登出时间
            sysAutoExit: 0
        }
    },
    getters: {},
    actions: {
        set<T extends keyof SysGlobalModel>(key: T, value: SysGlobalModel[T]) {
            Object.assign(this.$state, {
                [key]: value
            })
        },

        // 获取语言包
        async getLang() {
            const data = await maintenance.langTranslation.json.get()
            this.sysLang = data.langFlag

            const appLang: string = data.langFlag.toLowerCase()
            const langTranslation = data.langTranslation

            const esLang = formatLang(appLang)

            const elMessages = (localeList as any)[esLang]

            this.sysLangMessages = {
                [this.sysLang]: {
                    ...elMessages,
                    ...langTranslation
                }
            }
        }
    },
    persist: {
        key: 'SYS_GLOBAL',
        storage: SelfStorage,
        pick: [
            'sysLayout',
            'sysLang',
            'sysLangMessages',
            'sysColor',
            'sysDark',
            'sysMenuIsCollapse',
            'sysMenuUniqueOpened',
            'sysLayoutTags',
            'sysAutoExit'
        ]
    }
})
